package string_question.leecode.test132;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/8 9:49
 */
public class Solution2 {

    int min = Integer.MAX_VALUE;

    // 分割回文串
    public int minCut(String s) {
        // 首先用dp保存一个是否是回文串的记录
        boolean dp[][] = new boolean[s.length()][s.length()];
        for (int len = 1; len <= s.length(); len++) {
            for (int i = 0; i + len <= s.length(); i++) {
                int j = i + len - 1;
                if (len == 1) {
                    dp[i][j] = true;
                } else {
                    dp[i][j] = s.charAt(i) == s.charAt(j) && (len <= 3 || dp[i + 1][j - 1]);
                }
            }
        }
        dfs(s, 0, dp, new ArrayDeque<String>());
        return min;
    }

    private void dfs(String s, int c, boolean[][] dp, ArrayDeque<String> path) {
        if (c == s.length()) {
            min = Math.min(path.size() - 1, min);
            return;
        }
        for (int i = c; i < s.length(); i++) {
            if (dp[c][i]) {
                path.addLast(s.substring(c, i + 1));
                dfs(s, i + 1, dp, path);
                path.removeLast();
            }
        }
    }
}
